use std::{
    fs::File,
    io::{prelude::*, BufReader},
    path::Path,
};

use anyhow::anyhow;

pub fn read_lines<P>(path: P) -> anyhow::Result<Vec<String>>
where
    P: AsRef<Path>,
{
    let mut res = Vec::new();
    let file = File::open(path).unwrap();
    let fin = BufReader::new(file);

    for line in fin.lines() {
        res.push(line?);
    }

    Ok(res)
}

pub fn read_yaml(input: &Vec<String>) -> anyhow::Result<(usize, usize, String)> {
    const TOKEN: &str = "---";

    let match_index: Vec<usize> = input
        .iter()
        .enumerate()
        .filter(|(_, s)| s.trim().eq(TOKEN))
        .map(|(i, _)| i)
        .collect();

    if match_index.len() < 2 {
        return Err(anyhow!("match_index length must >= 2"));
    }

    let (from, to) = (match_index[0] + 1, match_index[1]);

    let s = input[match_index[0] + 1..match_index[1]].join("\r\n");

    Ok((from, to, s))
}

pub fn gen_toml(origin: Vec<String>, input: (usize, usize, String)) -> Vec<String> {
    let mut flag = true;
    let mut res = Vec::new();
    let (x, y, s) = input;
    let s = format!("+++\r\n{}+++", s);

    for (index, line) in origin.into_iter().enumerate() {
        if x - 1 <= index && index <= y {
            if flag {
                res.push(s.clone());
                flag = false;
            }
        } else {
            res.push(line);
        }
    }

    res
}
